package com.openapi.protocol.decode.subPackageHandle.mediaData;

import com.openapi.config.RedisConfig;
import com.openapi.data.JT808PackageData;
import com.openapi.data.JT808PushData;
import com.openapi.protocol.encode.Package808;
import com.openapi.protocol.decode.subPackageHandle.SubPackageHandle;
import com.openapi.protocol.decode.subPackageHandle.SubPackageStatus;
import exsun.jt808.data.config.jt808.Jt808ReceiveMsgTopic;
import exsun.jt808.data.distribute_data.jt808.MediaDataRsp;
import exsun.jt808.data.parseUtil.GpsUtil;
import exsun.jt808.data.upload_data.jt808.MediaFullData;
import exsun.jt808.data.util.parse.DecoderUtils;
import exsun.jt808.data.util.parse.HexStrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 多媒体数据解析
 */
@Component
public class MediaDataParse_0801 extends SubPackageHandle {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final RedisConfig redisConfig;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    public MediaDataParse_0801(RedisConfig redisConfig) {
        this.redisConfig = redisConfig;
    }


    public String getPakKey(JT808PackageData data) {
        //设备号_总包数作为key
        return data.dvo +"_"+ data.packageSize;
        //前提是分包按包序号传送，否则有问题
//        return data.dvo +"_"+ (data.msgSerialNo - data.packageIndex);
    }

    public List<JT808PushData> decode(JT808PackageData data){
        logger.info("接收多媒体数据：{}，{}，{}，{}",data.dvo, data.packageIndex, data.packageSize,data.msgSerialNo);
        List<JT808PushData> list =  new ArrayList<>();
        try {
            SubPackageStatus status = super.append(data);
            String key = getPakKey(data);
            // 检查缺失项，无缺失项,处理数据:存储、推送、应答
            if(status == SubPackageStatus.complete){
                //多媒体数据上传【完成】应答
                List<JT808PushData> bodys = rsp(data);
                list.addAll(bodys);
                byte[] totalBytes = super.getAllData(data);
                finished(data,  totalBytes);
                super.remove(key);
            }
            if(status == SubPackageStatus.receiving){
                //多媒体数据上传【通用】应答
                list.add(super.Response(data));
            }
            if(status == SubPackageStatus.missing){
                //多媒体数据上传【缺失】应答
                List<JT808PushData> bodys = rsp(data);
                list.addAll(bodys);
            }
            return list;
        }catch (Exception e){
            logger.error("多媒体解析异常：{}"+e.getMessage());
        }
        return list;
    }

    /**
     * 多媒体数据上传应答
     * @param data
     * @return
     */
    private List<JT808PushData> rsp(JT808PackageData data){
        List<JT808PushData> list = new ArrayList<>();
        List<Integer> miss = super.getMissItems(data);
        JT808PackageData firstPak = super.getPakage(data, 1);
        if(firstPak==null)return list;
        int mediaId = DecoderUtils.parseIntFromBytes(firstPak.getBodyBuffers(), 0, 4);
        MediaDataRsp rep = new MediaDataRsp(mediaId, miss);
        JT808PushData body = Package808.dediaDataRsp_0x8800(rep);
        list.add(body);
        return list;
    }


    private void finished(JT808PackageData data, byte[] totalBytes) throws Exception{
        //存储到ftp服务器
        MediaFullData sendData = parse(data, totalBytes);
        String filePath = MediaData_0x0801_Handle.getFilePath(sendData.dvo);
        String fileName = MediaData_0x0801_Handle.getFileName(sendData.dvo,sendData.getChannelId(),sendData.getMediaId(),sendData.getCodingType());
        String path = "ftp://" + jt808ServerConfig.getJt808FtpServer() + ":" + jt808ServerConfig.getJt808FtpPort() + filePath + "/" + fileName;
        sendData.setMediaPath(path);
        logger.info("多媒体存储至ftp...  {}", path);
        boolean result = MediaData_0x0801_Handle.saveToFTP(super.jt808ServerConfig, fileName, filePath, sendData.getMediaBytes());
        logger.info("多媒体存储" + (result == true?"成功:":"失败:") + path);
        sendData.setMediaBytes(null);
//        redisConfig.redisTemplate().opsForHash().put("mediaPte",sendData.dvo,sdf.format(sendData.pte));
//        HashOperations<String, String, String> hashOperations = this.redisConfig.redisTemplate().opsForHash();
//        logger.info(hashOperations.get("mediaPte",sendData.dvo));
        //推送数据
        super.kafkaService.push(sendData);
    }

    @Override
    public MediaFullData parse(JT808PackageData data, byte[] totalBodys) {
        MediaFullData obj = new MediaFullData();
        super.setResultObj(obj, data, Jt808ReceiveMsgTopic.mediaFullData);
        obj.setMediaId(DecoderUtils.parseIntFromBytes(totalBodys, 0, 4));
        obj.setMediaType(DecoderUtils.parseIntFromBytes(totalBodys, 4, 1));
        obj.setCodingType(DecoderUtils.parseIntFromBytes(totalBodys, 5, 1));
        obj.setEventType(DecoderUtils.parseIntFromBytes(totalBodys, 6, 1));
        obj.setChannelId(DecoderUtils.parseIntFromBytes(totalBodys, 7, 1));

        //兼容2011版协议
        String temp = HexStrUtil.encodeHex(DecoderUtils.byteCopy(totalBodys,8,2));
        //图片数据一般以这个开头
        if(temp.equals("ffd8")  ){
            //2011
            obj.setMediaBytes(DecoderUtils.byteCopy(totalBodys,8,totalBodys.length - 8));
        }else {
            try {
                //2013
                obj.setGpsData(GpsUtil.parseGps(DecoderUtils.byteCopy(totalBodys,8,28),false));
                obj.setMediaBytes(DecoderUtils.byteCopy(totalBodys,36,totalBodys.length - 36));
            }catch (Exception e){
                logger.error("多媒体解析错误 {} :{},{}",e.getMessage(),data.dvo,
                        HexStrUtil.encodeHex(totalBodys) );
            }
        }
        return obj;
    }
}
